//
//  ArticleViewController.m
//  Focus
//
//  Created by 楼主 on 14-11-4.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ArticleViewController.h"
#import "NetHandler.h"
#import "UIImageView+WebCache.h"
#import "AutoScrollView.h"
#import "webViewController.h"
#import "NoImageCell.h"
#import "OneImageCell.h"
#import "ThreeImageCell.h"
#import "Sub.h"

@interface ArticleViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, retain)NSDictionary *dataDic;  // 解析的总字典
@property (nonatomic, retain)AutoScrollView *autoScrollView;
@property (nonatomic, retain)NSMutableArray *arrTitle; //
@property (nonatomic, retain)UITableView *myTableView;
@property (nonatomic, retain)NSMutableArray *picArray;  // 存具体model的数组
@property (nonatomic, retain)NSMutableArray *secArray;  // 存section的数组
@property (nonatomic, retain)Sub *sub;
@end

@implementation ArticleViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        self.picArray = [NSMutableArray array];
        self.secArray = [NSMutableArray array];
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
    [_dataDic release];
    [_autoScrollView release];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.translucent = NO;
    self.dataDic = [NSDictionary dictionary];
#pragma mark 网络解析数据
    NSString *str = @"http://iphone.myzaker.com/zaker/topic.php?_appid=iphone&_bsize=640_1136&_dev=iPhone%2C7.1.2&_v=4.4.5&_version=4.52&app_id=11599&topic_id=";
    
    NSString *dataStr = [str stringByAppendingFormat:@"%@",self.ID];
#pragma mark 对请求下来的数据 创建modle类
    [NetHandler networkWithURL:dataStr comaletion:^(id result) {
        self.dataDic = [result objectForKey:@"data"];
        NSMutableArray *arrSec = [self.dataDic objectForKey:@"articles"];
        for (NSDictionary *dic in arrSec) {
            NSArray *arr = [dic objectForKey:@"list"];
            NSMutableArray *arrRow = [NSMutableArray array];
            for (NSDictionary *smallDic in arr) {
                Sub *sub = [[Sub alloc] init];
                sub.title = [[smallDic objectForKey:@"article"] objectForKey:@"title"];
                sub.auther_name = [[smallDic objectForKey:@"article"] objectForKey:@"auther_name"];
                sub.imageCount = [[smallDic objectForKey:@"article"] objectForKey:@"thumbnail_medias"];
                sub.webUrl = [[smallDic objectForKey:@"article"] objectForKey:@"weburl"];
                if ([sub.imageCount count] > 2) {
                    sub.m_url1 = [sub.imageCount[0] objectForKey:@"m_url"];
                    sub.m_url2 = [sub.imageCount[1] objectForKey:@"m_url"];
                    sub.m_url3 = [sub.imageCount[2] objectForKey:@"m_url"];
                } else if ([sub.imageCount count] == 1 || [sub.imageCount count] == 2) {
                    sub.m_url1 = [sub.imageCount[0] objectForKey:@"m_url"];
                }
                [arrRow addObject:sub];
            }
            [self.secArray addObject:arrRow];
        }
        
        [self createTableView];
    }];
}

#pragma mark  创建tableView
- (void)createTableView
{
    self.myTableView = [[[UITableView alloc]initWithFrame:self.view.frame]autorelease];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    NSArray *arr = [self.dataDic objectForKey:@"articles"];
    self.arrTitle = [NSMutableArray array];
    for (NSDictionary *dic in arr) {
        [self.arrTitle addObject:[dic objectForKey:@"title"]];
    }
    [self.view addSubview:self.myTableView];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 530, 320, 40)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    [view release];
    
#pragma mark 创建取消button
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    cancelButton.frame = CGRectMake(0, self.view.frame.size.height - 45, 50, 50);
    [cancelButton addTarget:self action:@selector(cancelButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [cancelButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    
//    UIButton *reportButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    
//    reportButton.frame = CGRectMake(self.view.frame.size.width - 50, self.view.frame.size.height - 45, 50, 50);
//    [reportButton addTarget:self action:@selector(reportButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//    [reportButton setImage:[UIImage imageNamed:@"iconfont-shuaxin.png"] forState:UIControlStateNormal];
//    
//    [self.view addSubview:reportButton];
    [self.view addSubview:cancelButton];
    
    [_myTableView release];
    [_autoScrollView release];
}
#pragma mark 取消button方法
- (void)cancelButtonAction:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark 刷新button方法
- (void)reportButtonAction:(UIButton *)button
{
//    [self.myTableView reloadData];
    [self viewDidAppear:YES];
}

#pragma mark 定义section的title
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    } else {
        NSString *str = self.arrTitle[section - 1];
        return str;
    }
}
#pragma mark 计算section里row的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    } else {
        NSMutableArray *arr = [self.dataDic objectForKey:@"articles"];
        NSDictionary *dic = arr[section - 1];
        NSMutableArray *arr1 = [dic objectForKey:@"list"];
        return [arr1 count];
    }
}
#pragma mark 计算section的个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.arrTitle.count + 1;
}
#pragma mark tableView里cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
    } else {
        
        Sub *sub = self.secArray[indexPath.section - 1][indexPath.row];
        webViewController *webVC = [[webViewController alloc]init];
        webVC.url = sub.webUrl;
        webVC.integer = 1;
        [self presentViewController:webVC animated:YES completion:^{
            
        }];
    }
    
}
#pragma mark 对tableView里cell的内容赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool"] autorelease];
    }
    if (indexPath.section == 0 ) {
        [self imageView];
        [self autoScroll];
        UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 240, 320, 80)];
        
        myLabel.text = [self.dataDic objectForKey:@"abstract"];
        myLabel.numberOfLines = 0;
        myLabel.font = [UIFont systemFontOfSize:11];
        
#pragma mark 点击cell无阴影效果
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [self.myTableView addSubview:myLabel];
        [myLabel release];
    }
    else {
        Sub *sub = self.secArray[indexPath.section - 1][indexPath.row];
#pragma mark cell里有三张照片
        if (sub.imageCount.count > 2) {
            ThreeImageCell *cellThree = [tableView dequeueReusableCellWithIdentifier:@"three"];
            
            if (cellThree == nil) {
                cellThree = [[[ThreeImageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"three"]autorelease];
            }
            cellThree.titleLabel.text = sub.title;
            cellThree.autherName.text = sub.auther_name;
            [cellThree.leftImage sd_setImageWithURL:[NSURL URLWithString:sub.m_url1]];
            [cellThree.minImage sd_setImageWithURL:[NSURL URLWithString:sub.m_url2]];
            [cellThree.rightImage sd_setImageWithURL:[NSURL URLWithString:sub.m_url3]];
            return cellThree;
        }
#pragma mark cell里有一张照片
        else if (sub.imageCount.count == 1 || sub.imageCount.count == 2) {
            OneImageCell *cellOne = [tableView dequeueReusableCellWithIdentifier:@"one"];
            
            if (cellOne == nil) {
                cellOne = [[[OneImageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"one"]autorelease];
            }
            cellOne.titleLabel.text = sub.title;
            cellOne.autherName.text = sub.auther_name;
            [cellOne.rightImage sd_setImageWithURL:[NSURL URLWithString:sub.m_url1]];
            return cellOne;
        }
#pragma mark cell里没有照片
        else {
            NoImageCell *cellNo = [tableView dequeueReusableCellWithIdentifier:@"none"];
            
            if (cellNo == nil) {
                cellNo = [[[NoImageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"none"]autorelease];
            }
            cellNo.titleLabel.text = sub.title;
            cellNo.autherName.text = sub.auther_name;
            return cellNo;
        }
    }
    return cell;
}

#pragma mark 创建滚动视图
- (void)autoScroll
{
    NSMutableArray *imageArray = [NSMutableArray array];
    NSMutableArray *titleArray = [NSMutableArray array];
    NSArray *scrollArray = [self.dataDic objectForKey:@"gallery"];
    for (NSDictionary *dic in scrollArray) {
        self.autoScrollView = [[AutoScrollView alloc]initWithFrame:CGRectMake(0, 60, 320, 180)];
        self.autoScrollView.timeInterval = 5;
        self.autoScrollView.pageControlAlignment = AutoScrollViewPageControlAlignmentCenter;
        [imageArray addObject:[dic objectForKey:@"promotion_img"]];
        [titleArray addObject:[dic objectForKey:@"title"]];
        [self.autoScrollView setTitleArray:titleArray];
        [self.autoScrollView setImageUrls:imageArray];
        [self.autoScrollView setTarget:self action:@selector(scrollViewTap:)];
        [self.myTableView addSubview:self.autoScrollView];
    }
}
#pragma mark 滚动视图的点击事件
- (void)scrollViewTap:(AutoScrollView *)sender
{
    NSArray *scrollArray = [self.dataDic objectForKey:@"gallery"];
    
    for (NSDictionary *dic in scrollArray) {
        dic = scrollArray[sender.pageNo];
        NSDictionary *dic1 = [dic objectForKey:@"article"];
        NSString *webUrl = [dic1 objectForKey:@"weburl"];
        webViewController *webVC = [[webViewController alloc]init];
        webVC.url = webUrl;
        webVC.integer = 1;
        
        [self presentViewController:webVC animated:YES completion:^{
            
        }];
    }
}

#pragma mark 对cell进行自适应高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0 && indexPath.section == 0) {
        return 240;
    } else if (indexPath.row == 1 && indexPath.section == 0)
    {
        CGRect rect = [[self.dataDic objectForKey:@"abstract"] boundingRectWithSize:CGSizeMake(500, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15]} context:nil];
        return rect.size.height;
    }
    Sub *sub = self.secArray[indexPath.section - 1][indexPath.row];
    if (sub.imageCount.count > 2){
        return 180;
    } else if (sub.imageCount.count == 1 || sub.imageCount.count == 2) {
        return 120;
    }
    return 100;
}
#pragma mark 创建顶部imageView
- (void)imageView
{
    NSString *strTitle = [[self.dataDic objectForKey:@"block_info"] objectForKey:@"title"];
    NSRange range = [strTitle rangeOfString:@"早读"];
    NSRange range1 = [strTitle rangeOfString:@"夜读"];
    if (range.location == NSNotFound || range1.location == NSNotFound) {
        UIImageView *myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 60)];
        myImageView.image = [UIImage imageNamed:@"change.png"];

        [self.myTableView addSubview:myImageView];
        [myImageView release];
    } else {
        NSDictionary *dic = [[self.dataDic objectForKey:@"block_info"]objectForKey:@"diy"];
        self.imageStr = [dic objectForKey:@"bgimage_url"];
        UIImageView *myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 60)];
        [myImageView sd_setImageWithURL:[NSURL URLWithString:self.imageStr]];
        [self.myTableView addSubview:myImageView];
        [myImageView release];
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
